package com.example.controller;

import com.example.anno.ApiLog;
import com.example.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;
import java.nio.charset.StandardCharsets;

/**
 * @Description:
 * @Author: WengYu
 * @CreateTime: 2022/06/01 00:12
 */
@RestController
@RequestMapping("/user")
@Api(tags = "测试类")
public class TestController {

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/hello")
    @ApiLog
    public String say(String hello) {
        return "来自服务端的问候" + hello;
    }

    /**
     * 要求使用 post请求，要求对User的code和password不可以为空，User类请自行定义，通过该方法学习对象传递
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登陆", httpMethod = "POST")
    public User login(@RequestBody @Valid User user) {
        return user;
    }

    @GetMapping("/test/{id}")
    @ApiOperation(value = "按id查询", httpMethod = "GET")
    public String findById(@PathVariable("id") Integer id) {
        return "来自服务端查找" + id;
    }

    @GetMapping("/baidu")
    public String visitBaidu() {
        String uri = "https://www.baidu.com/";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_HTML);
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        String strbody = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class).toString();
        return strbody;
    }
}
